<?php

namespace app\common\business;

use app\common\lib\Arr;
use app\common\model\mysql\SystemCategory;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Model;

class WorkType
{
    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\WorkType();
    }

    /**
     * 查询配置树
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAllTree(): array
    {
        $data=$this->model->getAllTree();
        return Arr::getTree($data);
    }

    /**
     * @param $where
     * @param $page
     * @param $limit
     * @param $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getListByWhere($where,$page,$limit,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    /**
     * 前端显示过滤掉没有子项的数据，否则导致小程序获取子项异常
     * @param $data
     * @return array
     */
    public function filterNoChildList($data){
        if (empty($data)){
            return [];
        }

        foreach ($data as $k=>$v){
            if (!isset($data[$k]['child']) || empty($data[$k]['child'])){
                unset($data[$k]);
            }
        }
        $data = array_values($data);
        return $data;
    }


    /**
     * 通过limit查询最顶级工种分类
     * @param $limit
     * @return \think\Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getParentListByLimit($limit){
        $where = [
            ['pid','=',0],
            ['status','=',config("status.mysql.table_normal")]
        ];
        $list = $this->model->getNormalListByLimit($where,$limit);
        return $list;
    }

    /**
     * 通过limit查询子级工种分类 并生成字典
     * @param $limit
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getChildDictionaries(): array
    {
        $where = [
            ['pid','<>',0],
            ['status','=',config("status.mysql.table_normal")]
        ];
        $list = $this->model->getNormalListByWhere($where);
        $list=$list->isEmpty()?[]:$list->toArray();
        $data=[];
        if(!empty($list)){
            foreach ($list as $v){
                $data[$v['id']]=$v;
            }
        }
        return $data;
    }

    /**
     * 新增/保存数据
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException|Exception
     */
    public function save($data): bool
    {
        if(empty($data['id'])){
            unset($data['id']);
        }
        return $this->model->saveData($data);
    }

    /**
     * 根据id修改状态
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function updateStatus($data): bool
    {
        if(empty($data['id'])){
            throw new Exception('参数错误');
        }
        return $this->model->updateStatus($data);
    }

    /**
     * 根据id删除
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function deleteById($id): bool
    {
        if(empty($id)){
            throw new Exception('参数错误');
        }
        $isChild=self::checkIsChild($id);
        if($isChild){
            throw new Exception('请先删除子级配置');
        }
        return $this->model->deleteById($id);
    }

    /**
     * 查询是否存在子级
     * @param $id
     * @return bool
     */
    public function checkIsChild($id): bool
    {
        return $this->model->where(['pid'=>$id])->count()>0;
    }

    /**
     * 查询字典
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function categoryDictionaries(): array
    {
        $data=$this->model->getDictionaries();
        $data=$data->isEmpty()?[]:$data->toArray();
        $newData=[];
        foreach ($data as $v){
            $newData[$v['id']]=$v['name'];
        }
        return $newData;
    }

    /**
     * 验证提交值是否有效值
     * @param $name
     * @param $value
     * @return bool
     * @throws Exception
     */
    public function checkValidValue($value){
        $dictionary = $this->categoryDictionaries();
        if (empty($dictionary)){
            throw new Exception('未查询到工种数据');
        }

        $flag = array_key_exists($value,$dictionary);
        if (!$flag){
            throw new Exception('工种类型异常');
        }
        return true;
    }

    /**
     * 验证提交逗号分割的多个值是否有效值
     * @param $value
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function checkValidValueMultiple($value){
        $dictionary = $this->categoryDictionaries();
        if (empty($dictionary)){
            throw new Exception('未查询到工种数据');
        }

        $valueArr = explode(',',$value);
        $diffArr = array_diff($valueArr,array_keys($dictionary));
        if (!empty($diffArr)){
            throw new Exception('工种类型异常');
        }
        return true;
    }
}
